$(document).ready(function() {
    //获得一级类别
    function getFirstCategory() {
        var result;
        $.ajax({
            type: "get",
            url: "/api/category/v/getFisrtCategory",
            async: false,
            processData: false,
            contentType: false,
            success: data => {
                if (data.success) {
                    result = JSON.parse(data.data);
                }else {
                    result = [];
                }
            },
            error: function (xhr, textStatus, errorThrown) {
                const msg = xhr.responseText;
                console.log(msg);
            }
        });
        return result;
    }

    //根据类名获得子类
    function getChildrenCategoryByName(name) {
        var result;
        var formData = new FormData();
        formData.append("name", name);
        $.ajax({
            type: "post",
            url: "/api/category/v/getChildrenCategoryByName",
            async: false,
            dataType: "text",
            data: formData,
            processData: false,
            contentType: false,
            success: data => {
                data = eval('('+ data +')');
                if (data.success) {
                    result = JSON.parse(data.data);
                }else {
                    result = [];
                }
            },
            error: function (xhr, textStatus, errorThrown) {
                const msg = xhr.responseText;
                console.log(msg);
            }
        });
        return result;
    }

    //获取类别
    function getCategory(id) {
        var result;
        var formData = new FormData();
        formData.append("id", id);
        $.ajax({
            type: "post",
            url: "/api/category/v/getCategoryById",
            async: false,
            dataType: "text",
            data: formData,
            processData: false,
            contentType: false,
            success: data => {
                data = eval('('+ data +')');
                if (data.success) {
                    result = JSON.parse(data.data);
                }else {
                    result = [];
                }
            },
            error: function (xhr, textStatus, errorThrown) {
                const msg = xhr.responseText;
                console.log(msg);
            }
        });
        return result;
    }

    function clickCategory(e) {
        var categoryName = $(e)[0].currentTarget.innerText;
        var secondCategoryList = getChildrenCategoryByName(categoryName);
        var parentNode = $(e)[0].target.parentNode;
        $(parentNode).children().removeClass("active");
        if (typeof(secondCategoryList)!=="undefined" && secondCategoryList.length>0) {
            $(".classify_list4").remove();
            var template = "<div class='f_left classify_list classify_list4'>";
            secondCategoryList.forEach(category => {
                template = template.concat("<a href='javascript:;' class=''>" + category.categoryName + "<i class='select-icon ivu-icon ivu-icon-ios-arrow-right' style='display: none;'></i></a>");
            })
            template = template.concat("</div>");
            $(".classify_box").append(template);
        }else{
            $(".classify_list4").remove();
            $(".modify_categoryInput").hide();
            var parentCategory = $("a.active");
            var name = "";
            for (var i=0;i<parentCategory.length;i++) {
                name = name.concat($("a.active")[i].innerText + " > ");
            }
            $(".category_text").text("图书 > " + name + categoryName);
            $(".kfz-confirm").toggle();
        }
        $(e)[0].target.classList.add("active");
    }

    function checkIsbn(ISBN) {
        var result;
        var formData = new FormData();
        formData.append("ISBN", ISBN);
        $.ajax({
            type: "post",
            url: "/api/book/u/checkISBN",
            async: false,
            dataType: "text",
            data: formData,
            processData: false,
            contentType: false,
            success: data => {
                data = eval('('+ data +')');
                if (data.success) {
                    result = JSON.parse(data.data);
                }else {
                    result = [];
                }
            },
            error: function (xhr, textStatus, errorThrown) {
                const msg = xhr.responseText;
                console.log(msg);
            }
        });
        return result;
    }

    function fillCategory() {
        var firstCategoryList = getFirstCategory();
        if (typeof(firstCategoryList)!=="undefined" && firstCategoryList.length>0)  {
            var template = "<div class='f_left classify_list classify_list3'>";
            firstCategoryList.forEach(category => {
                template = template.concat("<a href='javascript:;' class=''>" + category.categoryName + "<i class='select-icon ivu-icon ivu-icon-ios-arrow-right' style='display: none;'></i></a>");
            });
            template = template.concat("</div>");
            $(".classify_box").append(template);
        }
    }

    //图片上传
    function uploadImg(e) {
        console.log(e);
        var result;
        var formData = new FormData();
        var file = $(e)[0].files[0];
        formData.append("file", file);
        $.ajax({
            url: "/api/upload/v/img",
            type : 'POST',
            cache : false,
            data : formData,
            processData : false,
            contentType : false,
            success: data => {
                result=data.data;
                if (data.success) {
                    return result;
                }else {
                    console.log(data.msg)
                    return result;
                }
            },
            error: function (xhr, textStatus, errorThrown) {
                const msg = xhr.responseText;
                console.log(msg);
                return result;
            }
        })
    }

    function addStoreBook() {
        if (!flag) {
            return false;
        }
        getValue();
        $.ajax({
            type: "post",
            url: "/api/storeBook/u/addStoreBook",
            dataType: "text",
            contentType: "application/json;charset=UTF-8",
            data: JSON.stringify({
                "bookIsbn": bookIsbn,
                "number": bookCount,
                "img": bookImg,
                "price": bookPrice,
                "discountPrice": bookDiscountPrice,
                "introduction": bookIntroduction
            }),
            success: data => {
                data = eval('('+ data +')');
                if (data.success) {
                    location.reload();
                }else {
                    alert(data.msg);
                }
            },
            error: function (xhr, textStatus, errorThrown) {
                const msg = xhr.responseText;
                console.log(msg);
            }
        })
    }

    function getValue() {
        bookName = $("#bookName").val();
        bookIsbn = $("#bookIsbn").val();
        bookAuthor = $("#bookAuthor").val();
        bookPublisher = $("#bookPublisher").val();
        bookDiscountPrice = $("#bookDiscountPrice").val();
        bookCount = $("#bookCount").val();
        bookTime = $("#bookTime").val();
    }

    fillCategory();

    let flag = false;
    let bookName = $("#bookName").val();
    let bookIsbn = $("#bookIsbn").val();
    let bookAuthor = $("#bookAuthor").val();
    let bookPublisher = $("#bookPublisher").val();
    let bookDiscountPrice = $("#bookDiscountPrice").val();
    let bookCount = $("#bookCount").val();
    let bookTime = $("#bookTime").val();
    let bookPrice = $("#bookPrice").val();
    let bookIntroduction = $("#bookIntroduction").val();
    let bookImg = $("#bookImg").val();
    let imgFile = null;

    $(".classify_box").on("click", "a", clickCategory);

    $("#bookName").blur(() => {
        getValue();
        if (bookName==="") {
            $("#bookNameWarn").show();
            flag = false;
        }else {
            $("#bookNameWarn").hide();
            flag = true;
        }
    }).change(() => {
        getValue();
        if (bookName==="") {
            $("#bookNameWarn").show();
            flag = false;
        }else {
            $("#bookNameWarn").hide();
            flag = true;
        }
    });

    $("#bookIsbn").blur(() => {
        getValue();
        if (checkIsbn(bookIsbn)) {
            $("#ISBNWarn").show();
            flag = false;
        }else {
            $("#ISBNWarn").hide();
            flag = true;
        }
    }).change(() => {
        getValue();
        if (checkIsbn(bookIsbn)) {
            $("#ISBNWarn").show();
            flag = false;
        }else {
            $("#ISBNWarn").hide();
            flag = true;
        }
    });

    $("#bookAuthor").blur(() => {
        getValue();
        if (bookAuthor==="") {
            $("#authorWarn").show();
            flag = false;
        }else {
            $("#authorWarn").hide();
            flag = true;
        }
    }).change(() => {
        getValue();
        if (bookAuthor==="") {
            $("#authorWarn").show();
            flag = false;
        }else {
            $("#authorWarn").hide();
            flag = true;
        }
    });

    $("#bookPublisher").blur(() => {
        getValue();
        if (bookPublisher==="") {
            $("#publisherWarn").show();
            flag = false;
        }else {
            $("#publisherWarn").hide();
            flag = true;
        }
    }).change(() => {
        getValue();
        if (bookPublisher==="") {
            $("#publisherWarn").show();
            flag = false;
        }else {
            $("#publisherWarn").hide();
            flag = true;
        }
    });

    $("#bookDiscountPrice").blur(() => {
        getValue();
        if (bookDiscountPrice==="") {
            $("#discountPriceWarn").show();
            flag = false;
        }else {
            $("#discountPriceWarn").hide();
            flag = true;
        }
    }).change(() => {
        getValue();
        if (bookDiscountPrice==="") {
            $("#discountPriceWarn").show();
            flag = false;
        }else {
            $("#discountPriceWarn").hide();
            flag = true;
        }
    });

    $("#bookCount").blur(() => {
        getValue();
        if (bookCount==="") {
            $("#countWarn").show();
            flag = false;
        }else {
            $("#countWarn").hide();
            flag = true;
        }
    }).change(() => {
        getValue();
        if (bookCount==="") {
            $("#countWarn").show();
            flag = false;
        }else {
            $("#countWarn").hide();
            flag = true;
        }
    });

    $("#bookTime").blur(() => {
        getValue();
        if (bookTime==="") {
            $("#timeWarn").show();
            flag = false;
        }else {
            $("#timeWarn").hide();
            flag = true;
        }
    }).change(() => {
        getValue();
        if (bookTime==="") {
            $("#timeWarn").show();
            flag = false;
        }else {
            $("#timeWarn").hide();
            flag = true;
        }
    });

    $(".submit-btn").click(addStoreBook);
    $("#imageUploadBtn").click(selectFileEvent);

    function selectFileEvent() {
        let inputObj=document.createElement('input');
        inputObj.setAttribute('id','img_file');
        inputObj.setAttribute('type','file');
        inputObj.setAttribute("style",'visibility:hidden');
        $(inputObj).on("change", function(){
            selectFileChangeEvent(this.files);
        });
        document.body.appendChild(inputObj);
        inputObj.click();
    }

    function selectFileChangeEvent(files) {
        let boxFile = $("#imageList div.list-group").get(0);
        //判断是否有文件存在
        if (imgFile != null) {
            return false;
        }
        //获取图片路径
        let imgUrlStr = getImgUrlOfLocal(files[0]);
        let fileModel = getFileModel(files[0].name, imgUrlStr);
        $(boxFile).append(fileModel);
        initDeleteFile();
        imgFile = files[0];
    }

    function getImgUrlOfLocal(file) {
        // 获取文件路径
        let imgUrlStr = "";
        if (window.createObjectURL !== undefined) { //  basic
            imgUrlStr = window.createObjectURL(file);
        } else if (window.URL !== undefined) { // mozilla(firefox)
            imgUrlStr = window.URL.createObjectURL(file);
        } else if (window.webkitURL !== undefined) { // webkit or chrome
            imgUrlStr = window.webkitURL.createObjectURL(file);
        }
        return imgUrlStr;
    }

    function getFileModel(fileName,imgUrl) {
        return "<span class='image_item list-complete-item' style='' draggable='false'>" +
            "<div class='img'>" +
            "<img src='"+ imgUrl +"' alt='" + fileName + "' draggable='false'>" +
            "</div> " +
            "<div class='image_drag_mark'></div> " +
            "<div>" +
            "<div class='image_drag' style=''>" +
            "<div id='imgClose' class='iconfont icon-biaoqianshanb'></div>" +
            "</div>" +
            "<div class='img_bottom' style='display: none;'><!----> " +
            "<a href='javascript:;' class='img_bottom_edit' draggable='false'>编辑</a>" +
            "</div>" +
            "</div>" +
            "</span>"
    }

    function initDeleteFile() {
        let fileDeleteBtn = $("#imgClose");
        fileDeleteBtn.off();
        fileDeleteBtn.on("click", function () {
            deleteFileEvent(this);
        })
    }
    
    function deleteFileEvent(obj) {
        let fileItem = $(obj).parent().parent();
        imgFile = null;
        fileItem.remove();
    }

})